<?php

namespace framework\support;

use Exception;
use framework\support\Response;
use framework\support\Middleware;

class Router
{


    static function run()
    {
        $uri = $_SERVER['REQUEST_URI'];
        self::parse($uri);
    }

    static function parse($uri)
    {
        $controllerRoot = BasePath . '/app/controller';
        $default = "/index";
        $uriArray = explode('?', $uri);
        $path = $uriArray[0];
        if ($path == '/') {
            $path = $default;
        }
        return self::getControllerFile($path, $controllerRoot);
    }

    static function getControllerFile($path, $parentPath)
    {
        $request = request();

        $paths = explode('/', $path);
        $route = "";
        $tempPath = $parentPath;
        $params = [];
        for ($i = 1; $i < count($paths); $i++) {
            $route .= "/" . $paths[$i];
            $request->data('route', $route);
            $className = $paths[$i];
            $tempPath = $tempPath . DIRECTORY_SEPARATOR . $paths[$i];
            $phpFile = $tempPath . '.php';
            if (file_exists($phpFile)) {
                $funName = $paths[$i + 1] ?? 'index';
                if ($funName == '') $funName = "index";
                require_once $phpFile;
                try {
                    $controller = new $className();
                } catch (Exception $e) {
                    //self::handleException($e);
                    return;
                }

                if (method_exists($controller,  $funName)) {
                    $params = array_slice($paths, $i + 2);
                    if (count($params) > 0) {
                        try {
                            $controller->$funName(...$params);
                        } catch (Exception $e) {
                            self::handleException($e);
                        }
                        return;
                    } else {
                        return $controller->$funName();
                    }
                } else {
                    $method = strtolower($_SERVER['REQUEST_METHOD']);
                    $funName = $paths[$i + 1] ?? 'index';
                    if ($funName == '') $funName = "index";
                    $funName .= "_" . $method;
                    if (method_exists($controller,  $funName)) {
                        $params = array_slice($paths, $i + 2);
                        if (count($params) > 0) {
                            try {
                                $controller->$funName(...$params);
                            } catch (Exception $e) {
                                self::handleException($e);
                            }
                            return;
                        } else {
                            try {
                                $controller->$funName();
                            } catch (Exception $e) {
                                self::handleException($e);
                            }
                            return;
                        }
                    } else {
                        header('Content-Type: application/json; charset=utf-8');
                        echo json_encode([
                            'code' => 10002,
                            'msg' => "接口不存在",
                        ]);
                    }
                }
            }
        }
        header('Content-Type: application/json; charset=utf-8');
        header('HTTP/1.1 404');
    }

    static function handleException(Exception $e)
    {
        print($e->getMessage() . "\n");
        print($e->getTraceAsString());
        print("\n============\n");
    }
}
